<!-- 频谱分析图表组件 - 简洁版 -->
<template>
  <div class="spectrum-chart-container">
    <!-- 图表容器 -->
    <div ref="chartContainer" class="chart-container"></div>
    
    <!-- 简洁控制面板 -->
    <div class="spectrum-controls">
      <!-- 主要参数 -->
      <div class="main-controls">
        <div class="control-item">
          <span class="label">频率</span>
          <div class="value-input">
            <input 
              v-model="frequencyRange[0]" 
              type="number" 
              class="freq-input"
              @change="updateFrequencyRange"
            />
            <span class="separator">~</span>
            <input 
              v-model="frequencyRange[1]" 
              type="number" 
              class="freq-input"
              @change="updateFrequencyRange"
            />
            <span class="unit">MHz</span>
          </div>
        </div>
        
        <div class="control-item">
          <span class="label">阈值</span>
          <div class="threshold-control">
            <input 
              v-model="detectionThreshold" 
              type="range" 
              :min="-120" 
              :max="-30"
              class="threshold-slider"
              @input="updateThreshold"
            />
            <span class="threshold-value">{{ detectionThreshold }}dBm</span>
          </div>
        </div>
      </div>

      <!-- 快速选项 -->
      <div class="quick-controls">
        <div class="band-selector">
          <button 
            v-for="band in frequencyBands" 
            :key="band.name"
            :class="['band-btn', { active: isActiveBand(band) }]"
            @click="selectBand(band)"
          >
            {{ band.name }}
          </button>
        </div>
        
        <div class="mode-selector">
          <button 
            v-for="mode in analysisOptions"
            :key="mode.value"
            :class="['mode-btn', { active: analysisMode === mode.value }]"
            @click="setAnalysisMode(mode.value)"
          >
            {{ mode.label }}
          </button>
        </div>
      </div>
    </div>

    <!-- 信息显示 -->
    <div class="info-panel" v-if="selectedSignal">
      <div class="info-header">
        <div class="frequency-display">{{ selectedSignal.frequency }} MHz</div>
        <button class="close-btn" @click="closeSignalInfo">×</button>
      </div>
      <div class="info-content">
        <div class="info-row">
          <span class="info-key">功率</span>
          <span class="info-value">{{ selectedSignal.power }} dBm</span>
        </div>
        <div class="info-row">
          <span class="info-key">带宽</span>
          <span class="info-value">{{ selectedSignal.bandwidth }} MHz</span>
        </div>
        <div class="info-row">
          <span class="info-key">调制</span>
          <span class="info-value">{{ selectedSignal.modulation }}</span>
        </div>
      </div>
    </div>

    <!-- 状态指示器 -->
    <div class="status-indicators">
      <div class="indicator">
        <div class="indicator-value">{{ signalCount }}</div>
        <div class="indicator-label">信号</div>
      </div>
      <div class="indicator">
        <div class="indicator-value">{{ occupancyRate }}%</div>
        <div class="indicator-label">占用率</div>
      </div>
      <div class="indicator">
        <div class="indicator-value">{{ peakPower }}</div>
        <div class="indicator-label">峰值</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

// Props
const props = defineProps({
  frequencyData: {
    type: Array,
    default: () => []
  },
  selectedRange: {
    type: Array,
    default: () => [2000, 3000]
  }
})

// Emits
const emit = defineEmits(['frequencyChange', 'bandwidthSelect'])

// 组件引用
const chartContainer = ref(null)

// 图表实例
let chartInstance = null

// 响应式数据
const frequencyRange = ref([...props.selectedRange])
const detectionThreshold = ref(-80)
const analysisMode = ref('realtime')
const selectedSignal = ref(null)

// 频段预设
const frequencyBands = ref([
  { name: 'VHF', start: 30, end: 300 },
  { name: 'UHF', start: 300, end: 3000 },
  { name: '2.4G', start: 2400, end: 2500 },
  { name: '5G', start: 5150, end: 5850 },
  { name: '全频段', start: 0, end: 6000 }
])

// 分析模式选项
const analysisOptions = ref([
  { value: 'realtime', label: '实时' },
  { value: 'peak', label: '峰值' },
  { value: 'average', label: '平均' }
])

// 分析模式切换方法
const changeAnalysisMode = (mode) => {
  const modeNames = {
    realtime: '实时',
    peak: '峰值保持',
    average: '平均'
  }
  ElMessage.info(`分析模式: ${modeNames[mode]}`)
}

// 计算属性
const signalCount = computed(() => {
  if (!props.frequencyData) return 0
  return props.frequencyData.filter(point => point.power > detectionThreshold.value).length
})

const occupancyRate = computed(() => {
  if (!props.frequencyData || props.frequencyData.length === 0) return 0
  const occupiedPoints = props.frequencyData.filter(point => point.power > detectionThreshold.value).length
  return Math.round((occupiedPoints / props.frequencyData.length) * 100)
})

const peakPower = computed(() => {
  if (!props.frequencyData || props.frequencyData.length === 0) return '-'
  const maxPower = Math.max(...props.frequencyData.map(point => point.power))
  return `${maxPower.toFixed(1)}dBm`
})

// 判断当前频段是否激活
const isActiveBand = (band) => {
  return frequencyRange.value[0] === band.start && frequencyRange.value[1] === band.end
}

// 初始化图表
const initChart = () => {
  if (!chartContainer.value) return

  chartInstance = echarts.init(chartContainer.value, 'dark')
  
  const option = {
    backgroundColor: 'transparent',
    grid: {
      left: '5%',
      right: '5%',
      bottom: '10%',
      top: '5%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '频率 (MHz)',
      nameLocation: 'center',
      nameGap: 25,
      min: frequencyRange.value[0],
      max: frequencyRange.value[1],
      axisLine: {
        lineStyle: { color: 'rgba(0, 255, 136, 0.3)' }
      },
      axisLabel: {
        color: '#8591a3',
        fontSize: 11
      },
      splitLine: {
        lineStyle: { color: 'rgba(0, 255, 136, 0.1)' }
      }
    },
    yAxis: {
      type: 'value',
      name: '功率 (dBm)',
      nameLocation: 'center',
      nameGap: 40,
      axisLine: {
        lineStyle: { color: 'rgba(0, 255, 136, 0.3)' }
      },
      axisLabel: {
        color: '#8591a3',
        fontSize: 11
      },
      splitLine: {
        lineStyle: { color: 'rgba(0, 255, 136, 0.1)' }
      }
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: '#00ff88',
      borderWidth: 1,
      textStyle: { color: '#fff', fontSize: 12 },
      formatter: (params) => {
        const point = params[0]
        return `频率: ${point.data[0]} MHz<br/>功率: ${point.data[1]} dBm`
      }
    },
    series: [
      {
        name: '频谱',
        type: 'line',
        data: props.frequencyData.map(point => [point.frequency, point.power]),
        lineStyle: {
          color: '#00ff88',
          width: 1.5
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(0, 255, 136, 0.3)' },
              { offset: 1, color: 'rgba(0, 255, 136, 0.05)' }
            ]
          }
        },
        smooth: true,
        symbol: 'none',
        sampling: 'lttb'
      },
      // 阈值线
      {
        name: '阈值',
        type: 'line',
        data: [
          [frequencyRange.value[0], detectionThreshold.value],
          [frequencyRange.value[1], detectionThreshold.value]
        ],
        lineStyle: {
          color: '#ff6b6b',
          width: 1,
          type: 'dashed'
        },
        symbol: 'none',
        silent: true
      }
    ],
    animation: false
  }

  chartInstance.setOption(option)

  // 添加点击事件
  chartInstance.on('click', (params) => {
    if (params.seriesIndex === 0) {
      const frequency = params.data[0]
      const power = params.data[1]
      
      selectedSignal.value = {
        frequency: frequency.toFixed(2),
        power: power.toFixed(1),
        bandwidth: (Math.random() * 20 + 5).toFixed(1),
        modulation: ['AM', 'FM', 'PSK', 'QAM', 'OFDM'][Math.floor(Math.random() * 5)]
      }
      
      emit('frequencyChange', frequency)
    }
  })
}

// 更新图表数据
const updateChart = () => {
  if (!chartInstance) return

  const option = {
    xAxis: {
      min: frequencyRange.value[0],
      max: frequencyRange.value[1]
    },
    series: [
      {
        data: props.frequencyData.map(point => [point.frequency, point.power])
      },
      {
        data: [
          [frequencyRange.value[0], detectionThreshold.value],
          [frequencyRange.value[1], detectionThreshold.value]
        ]
      }
    ]
  }

  chartInstance.setOption(option)
}

// 频率范围更新
const updateFrequencyRange = () => {
  if (frequencyRange.value[0] >= frequencyRange.value[1]) {
    frequencyRange.value[1] = frequencyRange.value[0] + 100
  }
  updateChart()
  emit('bandwidthSelect', frequencyRange.value)
}

// 阈值更新
const updateThreshold = () => {
  updateChart()
}

// 选择频段
const selectBand = (band) => {
  frequencyRange.value = [band.start, band.end]
  updateChart()
  emit('bandwidthSelect', frequencyRange.value)
  ElMessage.success(`切换到${band.name}频段`)
}

// 设置分析模式
const setAnalysisMode = (mode) => {
  analysisMode.value = mode
  const modeNames = {
    realtime: '实时',
    peak: '峰值保持',
    average: '平均'
  }
  ElMessage.info(`分析模式: ${modeNames[mode]}`)
}

// 关闭信号信息
const closeSignalInfo = () => {
  selectedSignal.value = null
}

// 监听数据变化
watch(() => props.frequencyData, () => {
  updateChart()
}, { deep: true })

watch(() => props.selectedRange, (newRange) => {
  frequencyRange.value = [...newRange]
  updateChart()
})

// 窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 生命周期
onMounted(() => {
  nextTick(() => {
    initChart()
  })
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', handleResize)
})

// 暴露方法
defineExpose({
  updateChart,
  selectBand
})
</script>

<style scoped>
.spectrum-chart-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #0a0f1b 0%, #1a2332 100%);
  border-radius: 0.8vh;
  border: 1px solid rgba(0, 255, 136, 0.2);
  overflow: hidden;
}

/* 图表容器 */
.chart-container {
  flex: 1;
  min-height: 0;
  position: relative;
}

/* 控制面板 */
.spectrum-controls {
  padding: 1.5vh 2vw;
  background: rgba(0, 0, 0, 0.4);
  backdrop-filter: blur(10px);
  border-top: 1px solid rgba(0, 255, 136, 0.1);
}

.main-controls {
  display: flex;
  gap: 3vw;
  margin-bottom: 1.5vh;
}

.control-item {
  display: flex;
  align-items: center;
  gap: 1vw;
}

.label {
  font-size: 0.9rem;
  color: #8591a3;
  min-width: 3vw;
}

.value-input {
  display: flex;
  align-items: center;
  gap: 0.5vw;
}

.freq-input {
  width: 4vw;
  padding: 0.3vh 0.5vw;
  background: rgba(0, 255, 136, 0.1);
  border: 1px solid rgba(0, 255, 136, 0.3);
  border-radius: 0.3vh;
  color: #00ff88;
  font-size: 0.8rem;
  text-align: center;
}

.freq-input:focus {
  outline: none;
  border-color: #00ff88;
  box-shadow: 0 0 0 0.1vh rgba(0, 255, 136, 0.3);
}

.separator {
  color: #8591a3;
  margin: 0 0.3vw;
}

.unit {
  font-size: 0.8rem;
  color: #8591a3;
}

.threshold-control {
  display: flex;
  align-items: center;
  gap: 1vw;
}

.threshold-slider {
  width: 8vw;
  height: 0.3vh;
  background: rgba(0, 255, 136, 0.2);
  border-radius: 0.15vh;
  outline: none;
  -webkit-appearance: none;
}

.threshold-slider::-webkit-slider-thumb {
  width: 1vh;
  height: 1vh;
  background: #00ff88;
  border-radius: 50%;
  cursor: pointer;
  -webkit-appearance: none;
}

.threshold-value {
  font-size: 0.8rem;
  color: #00ff88;
  font-weight: 600;
  min-width: 4vw;
}

/* 快速控制 */
.quick-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.band-selector, .mode-selector {
  display: flex;
  gap: 0.5vw;
}

.band-btn, .mode-btn {
  padding: 0.5vh 1vw;
  background: rgba(0, 255, 136, 0.1);
  border: 1px solid rgba(0, 255, 136, 0.3);
  border-radius: 0.4vh;
  color: #8591a3;
  font-size: 0.8rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.band-btn:hover, .mode-btn:hover {
  background: rgba(0, 255, 136, 0.2);
  color: #00ff88;
  transform: translateY(-0.1vh);
}

.band-btn.active, .mode-btn.active {
  background: rgba(0, 255, 136, 0.3);
  border-color: #00ff88;
  color: #00ff88;
  box-shadow: 0 0 1vh rgba(0, 255, 136, 0.3);
}

/* 信息面板 */
.info-panel {
  position: absolute;
  top: 2vh;
  right: 2vw;
  width: 12vw;
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(0, 255, 136, 0.3);
  border-radius: 0.6vh;
  overflow: hidden;
  z-index: 100;
}

.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1vh 1.5vw;
  background: rgba(0, 255, 136, 0.1);
  border-bottom: 1px solid rgba(0, 255, 136, 0.2);
}

.frequency-display {
  font-size: 1rem;
  color: #00ff88;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  color: #8591a3;
  font-size: 1.2rem;
  cursor: pointer;
  padding: 0;
  width: 2vh;
  height: 2vh;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background: rgba(255, 107, 107, 0.2);
  color: #ff6b6b;
}

.info-content {
  padding: 1vh 1.5vw;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.5vh;
  font-size: 0.8rem;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-key {
  color: #8591a3;
}

.info-value {
  color: #00ff88;
  font-weight: 500;
}

/* 状态指示器 */
.status-indicators {
  position: absolute;
  bottom: 2vh;
  left: 2vw;
  display: flex;
  gap: 2vw;
  z-index: 100;
}

.indicator {
  background: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(5px);
  border: 1px solid rgba(0, 255, 136, 0.2);
  border-radius: 0.5vh;
  padding: 1vh 1.5vw;
  text-align: center;
  min-width: 4vw;
}

.indicator-value {
  font-size: 1.1rem;
  font-weight: 600;
  color: #00ff88;
  margin-bottom: 0.3vh;
}

.indicator-label {
  font-size: 0.7rem;
  color: #8591a3;
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .main-controls {
    flex-direction: column;
    gap: 1vh;
  }
  
  .quick-controls {
    flex-direction: column;
    gap: 1vh;
    align-items: stretch;
  }
  
  .info-panel {
    width: 15vw;
  }
  
  .status-indicators {
    flex-direction: column;
    gap: 1vh;
  }
}
</style>